import { PasswordFreeLogin } from "../utils/DDlogin.js";
import store from '../store/index.js';


const BASE_URL = "http://113.135.192.25:18398/api"; // 端口地址
// const BASE_URL ="https://discipline-api.herinapp.com" //测试环境
const missAuth = () => {
  uni.removeStorageSync("token");
  uni.removeStorageSync("userInfo");
  uni.hideLoading();
};

const getNetworkType = () => {
	return new Promise((resolve) => {
		uni.getNetworkType({
			complete: res => resolve(res)
		})
	})
}

const herinRequist = async ({ url, method, data, contentType }) => {
  // 获取网络状态
  
  const {networkAvailable} = await getNetworkType()
  if(!networkAvailable) {
	  const curr = Date.now()
	  if(!store.state.network || curr > store.state.network ) {
		  store.state.network = curr + 3000
		  uni.showModal({
		    title: "网络状况",
		    content: "请检查您当前网络状态",
		    showCancel: true,
		    cancelText: "返回",
		    confirmText: "重新刷新",
		    success(res) {                                           
		  	if (res.confirm) {
		  		
		  	  const page = getCurrentPages();
		  	  uni.redirectTo({
		  		url: page[page.length - 1].$page.fullPath,
		  	  });
		  	  store.state.network = true
		  	} else if (res.cancel) {
		  		 store.state.network = false
		  	  uni.navigateBack({
		  		delta: 1,
		  	  });
		  	}
		    },
		  });	  
	  }	
	  return
  } else {
		store.state.network = 0
  }

  // 判断token是否过期
  try {
    const userInfo = JSON.parse(uni.getStorageSync("userInfo"));
    if (+new Date() > userInfo.exp * 1000) {
      missAuth();
    }
  } catch (e) {
  }
  let types = "";
  if (method === "POST" && !contentType) {
    types = "application/x-www-form-urlencoded";
  } else if (method === "POST" && contentType) {
    types = contentType;
  } else {
    types = "application/json";
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url,
      method: method || "GET",
      data: data || {},
      timeout: 30000,
      // 添加请求头 携带token
      header: {
        "Content-Type": types,
        Accept: "application/json, text/javascript, */*; q=0.01",
        Authorization: uni.getStorageSync("token"),
      },
      success: (res) => {
        if (res.data.data?.token) {
          // 存储token
          uni.setStorageSync("token", "Bearer " + res.data.data.token);
        }
        if (!res.data.success && res.data.msg === "No Auth") {
          missAuth();
        }
        let code = res.data.code;
        switch (code) {
          // 失去权限重新登录
          case 401:
            missAuth();
            break;
        }
        resolve(res.data);
      },
      fail: (err) => {
        uni.hideLoading();
        if (!err.data?.success && err.data?.msg === "No Auth") {
          missAuth();
        } else if (err.statusCode === 401) {
          missAuth();
        }
        reject(err);
		uni.showToast({
											title: '您的请求超时',
											icon: 'none',
										})
      },
      complete: () => {},
    });
  });
};

export { herinRequist, BASE_URL };
